package org.orz.story.pms.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.orz.cloud.common.enums.AliveFlagEnum;
import org.orz.story.pms.api.model.dto.AccountWorkbenchListDto;
import org.orz.story.pms.api.model.vo.AccountWorkbenchListVo;
import org.orz.story.pms.biz.persistence.entities.PmsAccount;
import org.orz.story.pms.biz.persistence.entities.PmsAccountWorkbench;
import org.orz.story.pms.biz.persistence.entities.PmsWorkbench;
import org.orz.story.pms.biz.persistence.mappers.PmsAccountMapper;
import org.orz.story.pms.biz.persistence.mappers.PmsAccountWorkbenchMapper;
import org.orz.story.pms.biz.persistence.mappers.PmsWorkbenchMapper;
import org.orz.story.pms.biz.service.PmsWorkbenchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class PmsWorkbenchServiceImpl implements PmsWorkbenchService {
    @Autowired
    private PmsAccountWorkbenchMapper pmsAccountWorkbenchMapper;
    @Autowired
    private PmsWorkbenchMapper pmsWorkbenchMapper;
    @Autowired
    private PmsAccountMapper pmsAccountMapper;

    @Override
    public List<AccountWorkbenchListVo> getAccountWorkbenchList(AccountWorkbenchListDto dto) {
        PmsAccount pmsAccount = pmsAccountMapper.selectOne(new LambdaQueryWrapper<PmsAccount>()
                .eq(PmsAccount::getMemAccountId, dto.getAccountId())
                .eq(PmsAccount::getAliveFlag, AliveFlagEnum.ALIVE.getKey()));
        if(pmsAccount == null){
            return Collections.emptyList();
        }

        List<PmsAccountWorkbench> pmsAccountWorkbenches = pmsAccountWorkbenchMapper.selectList(new LambdaQueryWrapper<PmsAccountWorkbench>()
                .eq(PmsAccountWorkbench::getAccountId, pmsAccount.getId())
                .eq(PmsAccountWorkbench::getAliveFlag, AliveFlagEnum.ALIVE.getKey()));
        if(CollUtil.isEmpty(pmsAccountWorkbenches)){
            return Collections.emptyList();
        }

        Set<Long> workbenchIds = pmsAccountWorkbenches.stream().map(PmsAccountWorkbench::getWorkbenchId).collect(Collectors.toSet());

        List<PmsWorkbench> pmsWorkbenches = pmsWorkbenchMapper.selectBatchIds(workbenchIds);
        return pmsWorkbenches.stream().map(item -> {
            AccountWorkbenchListVo vo = new AccountWorkbenchListVo();
            BeanUtil.copyProperties(item, vo);
            return vo;
        }).collect(Collectors.toList());
    }
}
